import React, { useState } from 'react';
import { useThemeStore } from '../stores/themeStore';
import { getTheme } from '../theme/config';

interface LLMModel {
  id: number;
  name: string;
  provider: string;
  llm_model_id: string;
  max_tokens: number;
  temperature: number;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface ModelChatProps {
  selectedModel: LLMModel | null;
}

const ModelChat: React.FC<ModelChatProps> = ({ selectedModel }) => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [question, setQuestion] = useState('');
  const [answer, setAnswer] = useState('');
  const [conversationId, setConversationId] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [sending, setSending] = useState(false);
  
  const handleAskQuestion = () => {
    if (!selectedModel || !question.trim()) return;
    
    const token = localStorage.getItem('access_token');
    if (!token) {
      return;
    }
    
    // 清除之前的回答
    setAnswer('');
    setSending(true);
    setError(null);
    
    // 如果还没有对话ID，先创建对话
    if (!conversationId) {
      fetch('/api/v1/llm/conversations', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          title: `对话-${new Date().toLocaleString()}`,
          llm_model_id: selectedModel.id
        })
      })
      .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('创建对话失败');
        }
      })
      .then(data => {
        setConversationId(data.id);
        // 创建对话后发送消息
        sendMessage(data.id);
      })
      .catch(error => {
        console.error('Error creating conversation:', error);
        setError(error.message || '创建对话时发生未知错误');
        setSending(false);
      });
    } else {
      // 直接发送消息
      sendMessage(conversationId);
    }
  };
  
  const sendMessage = (convId: number) => {
    const token = localStorage.getItem('access_token');
    if (!token) {
      return;
    }
    
    fetch('/api/v1/llm/chat', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        conversation_id: convId,
        message: question
      })
    })
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('发送消息失败');
      }
    })
    .then(data => {
      setAnswer(data.message);
      setError(null);
      setSending(false);
    })
    .catch(error => {
      console.error('Error sending message:', error);
      setError(error.message || '发送消息时发生未知错误');
      setSending(false);
    });
  };
  
  if (!selectedModel) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100%',
        color: theme.textSecondary
      }}>
        <p>请选择一个模型开始对话</p>
      </div>
    );
  }
  
  return (
    <div style={{
      position: 'relative',
      width: '100%',
      height: '100%',
      color: theme.textPrimary
    }}>
      <h2 style={{ 
        color: theme.textPrimary,
        marginBottom: '20px'
      }}>与 {selectedModel.name} 对话</h2>
      <div style={{ marginTop: '20px' }}>
        <textarea
          value={question}
          onChange={(e) => setQuestion(e.target.value)}
          placeholder="请输入您的问题..."
          style={{
            width: '100%',
            height: '100px',
            backgroundColor: theme.inputBackground,
            border: `1px solid ${theme.borderColor}`,
            borderRadius: '10px',
            padding: '10px',
            color: theme.textPrimary,
            resize: 'vertical'
          }}
        />
        <button
          onClick={handleAskQuestion}
          disabled={!question.trim() || sending}
          style={{
            marginTop: '10px',
            padding: '10px 20px',
            backgroundColor: theme.primaryColor,
            color: theme.buttonTextColor,
            border: 'none',
            borderRadius: '5px',
            cursor: (!question.trim() || sending) ? 'not-allowed' : 'pointer',
            opacity: (!question.trim() || sending) ? 0.5 : 1,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          {sending ? (
            <>
              <div style={{
                width: '16px',
                height: '16px',
                border: `2px solid ${theme.buttonTextColor}`,
                borderTop: '2px solid transparent',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite',
                marginRight: '8px'
              }}></div>
              发送中...
            </>
          ) : '发送'}
        </button>
      </div>
      
      {answer && (
        <div style={{ marginTop: '20px' }}>
          <h3 style={{ 
            color: theme.textPrimary,
            marginBottom: '10px'
          }}>回答:</h3>
          <div style={{
            backgroundColor: theme.siderBackground,
            border: `1px solid ${theme.borderColor}`,
            borderRadius: '10px',
            padding: '15px',
            marginTop: '10px'
          }}>
            <p style={{ 
              color: theme.textPrimary,
              lineHeight: '1.6'
            }}>{answer}</p>
          </div>
        </div>
      )}
      
      {error && (
        <div style={{
          marginTop: '20px',
          color: '#ff6b6b',
          padding: '10px',
          backgroundColor: 'rgba(255, 107, 107, 0.1)',
          border: '1px solid #ff6b6b',
          borderRadius: '5px'
        }}>
          错误: {error}
        </div>
      )}
      
      {/* 添加旋转动画的样式 */}
      <style>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
};

export default ModelChat;